﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using TjZheng.Controls;
using TjZheng.Domain.Business;
using TjZheng.Domain.DataEntity;
using TjZheng.Framework;

namespace TjZheng.Controls
{
    public static class UploadExtension
    {
        static Dictionary<int, KeyValuePair<string, string>> UpLoadTypeDict { get; set; }
        static Dictionary<string, UpLoadBase> UpLoadBaseDict { get; set; }
        static UploadExtension()
        {
            UpLoadTypeDict = new Dictionary<int, KeyValuePair<string, string>> { { 0, new KeyValuePair<string, string>("TjZheng.Controls", "TjZheng.Controls.NativeUpLoad") }, { 1, new KeyValuePair<string, string>("TjZheng.Controls", "TjZheng.Controls.FtpUpLoad") } };
            UpLoadBaseDict = new Dictionary<string, UpLoadBase>();
        }
        public static void AddOrReplaceUpLoadBase(int identity, KeyValuePair<string, string> keyValue)
        {
            KeyValuePair<string, string> _keyValue;
            if (UpLoadTypeDict.TryGetValue(identity, out _keyValue))
            {
                UpLoadTypeDict[identity] = keyValue;
            }
            else
            {
                UpLoadTypeDict.Add(identity, keyValue);
            }
        }
        /// <summary>
        /// 上传文件保存
        /// </summary>
        /// <param name="value">原上传路径</param>
        /// <param name="filename">文件的name属性</param>
        /// <param name="setname">前端构建的配置实体UpLoadSet</param>
        /// <param name="responseUrls">自定义响应地址</param>
        /// <returns></returns>
        public static string SaveFiles(this string value, string filename, string setname)
        {
            var Request = HttpContext.Current.Request;
            var objFiles = Request.Files.GetMultiple(filename);
            if (objFiles.IsNull())
            {
                return value ?? string.Empty;
            }
            var objFile = objFiles.SingleOrDefault();
            if (objFile != null && objFile.FileName.IsNull())
            {
                return value ?? string.Empty;
            }
            return SaveFilesAsList(filename, setname).JoinString("$");
        }
        /// <summary>
        /// 上传文件保存
        /// </summary>
        /// <param name="filename">文件的name属性</param>
        /// <param name="setname">前端构建的配置实体UpLoadSet</param>
        /// <returns></returns>
        public static List<string> SaveFilesAsList(this string filename, string setname)
        {
            var Request = HttpContext.Current.Request;
            var objFiles = Request.Files.GetMultiple(filename);
            List<string> objList = new List<string>();
            if (objFiles.IsNull())
            {
                return objList;
            }
            InvokeResult objInvokeResult = null;
            if (Request[setname].IsNull())
            {
                return objList;
            }
            UpLoadSet objUpLoadSet = string.Format("[{0}]", Request[setname]).JsonDeserialize<List<UpLoadSet>>().FirstOrDefault();
            if (objFiles.Count == 1)
            {
                objInvokeResult = objFiles.Single().SaveFile(objUpLoadSet);
                if (objInvokeResult.Data != null)
                {
                    objList.Add(objInvokeResult.Data.ToString());
                }
                return objList;
            }
            foreach (var objFile in objFiles)
            {
                objInvokeResult = objFile.SaveFile(objUpLoadSet);
                if (objInvokeResult.Data != null)
                {
                    objList.Add(objInvokeResult.Data.ToString());
                }
            }
            return objList;
        }
        /// <summary>
        /// 上传文件保存
        /// </summary>
        /// <param name="uploadFileBytes">上传文件总字节</param>
        /// <param name="fileExtension">文件后缀</param>
        /// <param name="objUploadLimit">数据库读取的配置实体</param>
        /// <returns></returns>
        public static string SaveFile(this byte[] uploadFileBytes, string fileExtension, UploadLimit objUploadLimit)
        {
            if (uploadFileBytes.IsNull() || objUploadLimit == null)
            {
                return string.Empty;
            }
            UpLoadBase objUpLoadBase = CreateUpLoadBase(objUploadLimit);
            return objUpLoadBase.SaveFile(uploadFileBytes, fileExtension);
        }
        /// <summary>
        /// 上传文件保存
        /// </summary>
        /// <param name="objInputStream">上传文件流</param>
        /// <param name="fileExtension">文件后缀</param>
        /// <param name="objUploadLimit">数据库读取的配置实体</param>
        /// <returns></returns>
        public static string SaveFile(this Stream objInputStream, string fileExtension, UploadLimit objUploadLimit)
        {
            if (objInputStream == null || objUploadLimit == null)
            {
                return string.Empty;
            }
            UpLoadBase objUpLoadBase = CreateUpLoadBase(objUploadLimit);
            return objUpLoadBase.SaveFile(objInputStream, fileExtension);
        }
        /// <summary>
        /// 上传文件保存（MVC）
        /// </summary>
        /// <param name="objFile">上传文件</param>
        /// <param name="objUploadLimit">数据库读取的配置实体</param>
        /// <returns></returns>
        public static string SaveFile(this HttpPostedFileBase objFile, UploadLimit objUploadLimit)
        {
            if (objFile == null || objUploadLimit == null)
            {
                return string.Empty;
            }
            UpLoadBase objUpLoadBase = CreateUpLoadBase(objUploadLimit);
            return objUpLoadBase.SaveFile(objFile);
        }
        /// <summary>
        /// 上传文件保存
        /// </summary>
        /// <param name="objFile">上传文件</param>
        /// <param name="objUploadLimit">数据库读取的配置实体</param>
        /// <returns></returns>
        public static string SaveFile(this HttpPostedFile objFile, UploadLimit objUploadLimit)
        {
            if (objFile == null || objUploadLimit == null)
            {
                return string.Empty;
            }
            UpLoadBase objUpLoadBase = CreateUpLoadBase(objUploadLimit);
            return objUpLoadBase.SaveFile(objFile);
        }
        /// <summary>
        /// 上传文件保存（MVC）
        /// </summary>
        /// <param name="objFile">上传文件</param>
        /// <param name="setname">前端构建的配置实体UpLoadSet</param>
        /// <returns></returns>
        public static InvokeResult SaveFile(this HttpPostedFileBase objFile, string setname)
        {
            var Request = HttpContext.Current.Request;
            InvokeResult objInvokeResult = new InvokeResult();
            if (Request[setname].IsNull())
            {
                objInvokeResult.ResultCode = "ParamsEmpty";
                objInvokeResult.ResultMessage = "上传配置参数不能为空";
                return objInvokeResult;
            }
            var objUpLoadSet = Request[setname].JsonDeserialize<UpLoadSet>();
            if (objUpLoadSet == null)
            {
                objInvokeResult.ResultCode = "ParamsError";
                objInvokeResult.ResultMessage = "上传配置参数格式错误";
                return objInvokeResult;
            }
            BizUploadLimit objBizUploadLimit = new BizUploadLimit();
            UploadLimit objUploadLimit = null;

            if (objUpLoadSet.ULId > 0)
            {
                objUploadLimit = objBizUploadLimit.GetRecord(objUpLoadSet.ULId);
            }
            else
            {
                if (objUpLoadSet.CategoryCode.IsNoNull() && objUpLoadSet.LimitCode.IsNoNull())
                {
                    objUploadLimit = objBizUploadLimit.GetRecord(string.Format("UcCode='{0}' AND LimitCode='{1}'", objUpLoadSet.CategoryCode, objUpLoadSet.LimitCode));
                }
            }
            if (objUploadLimit == null)
            {
                objInvokeResult.ResultCode = "ParamsEmpty";
                objInvokeResult.ResultMessage = "上传配置参数不能为空";
                return objInvokeResult;
            }
            if (objUploadLimit.UcCode.IsNull() || objUploadLimit.LimitCode.IsNull())
            {
                objInvokeResult.ResultCode = "ParamsError";
                objInvokeResult.ResultMessage = "上传配置参数格式错误";
                return objInvokeResult;
            }
            string fileExtension = Path.GetExtension(objFile.FileName);
            if (fileExtension.IsNull() || !objUploadLimit.LimitExtension.ToLower().Contains(fileExtension.ToLower().Replace(".", "")))
            {
                objInvokeResult.ResultCode = "FormatError";
                objInvokeResult.ResultMessage = objUploadLimit.LimitExtension.FormatSelf("上传文件的格式不正确，文件格式应为{0}");
                return objInvokeResult;
            }
            int filesize = objFile.ContentLength;
            if (objUploadLimit.LimitSize > 0 && filesize > objUploadLimit.LimitSize * 1024)
            {
                objInvokeResult.ResultCode = "SizeError";
                objInvokeResult.ResultMessage = objUploadLimit.LimitSize.ToString().FormatSelf("上传文件的格大小过大，文件大小应为{0}K");
                return objInvokeResult;
            }
            objInvokeResult.ResultCode = "Success";
            objInvokeResult.ResultMessage = "上传成功";
            objInvokeResult.Data = objFile.SaveFile(objUploadLimit);
            return objInvokeResult;
        }
        /// <summary>
        /// 上传文件保存
        /// </summary>
        /// <param name="objFile">上传文件</param>
        /// <param name="objUpLoadSet">前端构建的配置实体UpLoadSet</param>
        /// <returns></returns>
        public static InvokeResult SaveFile(this HttpPostedFile objFile, UpLoadSet objUpLoadSet)
        {
            var Request = HttpContext.Current.Request;
            InvokeResult objInvokeResult = new InvokeResult();
            if (objUpLoadSet == null)
            {
                objInvokeResult.ResultCode = "ParamsError";
                objInvokeResult.ResultMessage = "上传配置参数格式错误";
                return objInvokeResult;
            }
            BizUploadLimit objBizUploadLimit = new BizUploadLimit();
            UploadLimit objUploadLimit = null;

            if (objUpLoadSet.ULId > 0)
            {
                objUploadLimit = objBizUploadLimit.GetRecord(objUpLoadSet.ULId);
            }
            else
            {
                if (objUpLoadSet.CategoryCode.IsNoNull() && objUpLoadSet.LimitCode.IsNoNull())
                {
                    objUploadLimit = objBizUploadLimit.GetRecord(string.Format("UcCode='{0}' AND LimitCode='{1}'", objUpLoadSet.CategoryCode, objUpLoadSet.LimitCode));
                }
            }
            if (objUploadLimit == null)
            {
                objInvokeResult.ResultCode = "ParamsEmpty";
                objInvokeResult.ResultMessage = "上传配置参数不能为空";
                return objInvokeResult;
            }
            if (objUploadLimit.UcCode.IsNull() || objUploadLimit.LimitCode.IsNull())
            {
                objInvokeResult.ResultCode = "ParamsError";
                objInvokeResult.ResultMessage = "上传配置参数格式错误";
                return objInvokeResult;
            }
            string fileExtension = Path.GetExtension(objFile.FileName);
            if (fileExtension.IsNull() || !objUploadLimit.LimitExtension.ToLower().Contains(fileExtension.ToLower().Replace(".", "")))
            {
                objInvokeResult.ResultCode = "FormatError";
                objInvokeResult.ResultMessage = objUploadLimit.LimitExtension.FormatSelf("上传文件的格式不正确，文件格式应为{0}");
                return objInvokeResult;
            }
            int filesize = objFile.ContentLength;
            if (objUploadLimit.LimitSize > 0 && filesize > objUploadLimit.LimitSize * 1024)
            {
                objInvokeResult.ResultCode = "SizeError";
                objInvokeResult.ResultMessage = objUploadLimit.LimitSize.ToString().FormatSelf("上传文件的格大小过大，文件大小应为{0}K");
                return objInvokeResult;
            }
            objInvokeResult.ResultCode = "Success";
            objInvokeResult.ResultMessage = "上传成功";
            objInvokeResult.Data = objFile.SaveFile(objUploadLimit);
            return objInvokeResult;
        }
        static UpLoadBase CreateUpLoadBase(UploadLimit objUploadLimit)
        {
            KeyValuePair<string, string> keyValue = UpLoadTypeDict[objUploadLimit.SaveType];
            UpLoadBase objUpLoadBase = null;
            if (!UpLoadBaseDict.TryGetValue(keyValue.Key + keyValue.Value, out objUpLoadBase))
            {
                objUpLoadBase = Reflector.CreateInstace(keyValue.Value, keyValue.Key, objUploadLimit) as UpLoadBase;
                if (objUpLoadBase != null)
                {
                    UpLoadBaseDict[keyValue.Key + keyValue.Value] = objUpLoadBase;
                }
            }
            return objUpLoadBase;
        }
    }
}
